const axios = require("axios").default;
const cookie = require("cookie");
const set_cookie_p = require("set-cookie-parser");
const CommonAxerrHandlerGen = require("../CommonAxerrHandler");
const FormData = require("form-data");


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{cookie:String}}>}
 */
function getCookieText() {
  return new Promise(async resolve => {
    let o_fromCookiesLibluMe = await getPhpsessid();
    if (!o_fromCookiesLibluMe.ok) {
      return resolve({
        ok: false,
        msg: `can not get phpsessid:${o_fromCookiesLibluMe.msg}`
      })
    }
    let phpsessid = o_fromCookiesLibluMe.data.phpsessid;
    axios.get("https://www.soyoung.com/post/pubvideopost", {
      headers: {
        cookie: `PHPSESSID=${phpsessid}; `,
        Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
      },
      validateStatus: s => s == 200 || String(s).startsWith("3"),
      maxRedirects: 0
    }).then(axresp => {
      if (axresp.status == 200) {
        let cookies_obj = {
          "PHPSESSID": phpsessid
        };
        if (axresp.headers["set-cookie"] && Array.isArray(axresp.headers["set-cookie"])) {
          let o_parse = set_cookie_p(axresp.headers["set-cookie"]);
          for (let p of o_parse) {
            cookies_obj[p.name] = p.value
          }
        }
        let cookie_strs = [];
        for (let cookie_name in cookies_obj) {
          cookie_strs.push(cookie.serialize(cookie_name, cookies_obj[cookie_name], {
            encode: s => s
          }));
        }
        resolve({
          ok: true,
          msg: "ok",
          data: {
            cookie: cookie_strs.join("; ")
          }
        })
      } else {
        return CommonAxerrHandlerGen(resolve)(`failed to surf with PHPSESSID[${phpsessid}],\nstatus is ${axresp.status}`)
      }
    }).catch(axerr => {
      CommonAxerrHandlerGen(resolve)(axerr);
    })
  })
}

/**
 * @param {String} cookie_str
 * @returns {Promise<{ok:Boolean,msg:string,data:{uptoken:String}}>}
 */
function __getQiniuTokenSingle(cookie_str) {
  return new Promise(async resolve => {
    let form = new FormData;
    form.append("type", 2);
    form.append("sys", 0);
    form.append("watermark", 1);

    axios.post("https://www.soyoung.com/editor/token", form, {
      headers: {
        ...form.getHeaders(),
        cookie: cookie_str,
        Origin: 'https://www.soyoung.com',
        "X-Requested-With": "XMLHttpRequest",
        Referer: 'https://www.soyoung.com/post/pub_calendar/group_id/9226624',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.107'
      },
      validateStatus: s => s == 200
    }).then(axresp => {
      if (axresp.data.errorCode === 0
        && axresp.data.responseData
        && axresp.data.responseData.token) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            uptoken: axresp.data.responseData.token
          }
        })
      }

      CommonAxerrHandlerGen(resolve)(axresp.data)
    }).catch(axerr => {
      CommonAxerrHandlerGen(resolve)(axerr);
    })
  })
}

let cache_cookie_p = getCookieText();

/**
 * 
 * @returns {Promise<{ok:Boolean,msg:string,data:{uptoken:String}}>}
 */
function getQiniuToken() {
  return new Promise(async resolve => {
    if (cache_cookie_p) {
      for (let re = 1; re <= 5; re++) {
        let o_cookie = await cache_cookie_p;
        if ((!o_cookie.ok)) {
          if (re == 5) {
            cache_cookie_p = null;
            return resolve({
              ok: false,
              msg: `get cookie text failed:${o_cookie.msg}`
            })
          } else {
            continue;
          }
        }
        let o_token_single = await __getQiniuTokenSingle(o_cookie.data.cookie);
        if (!o_token_single.ok) {
          if (re == 5) {
            cache_cookie_p = null;
            return resolve({
              ok: false,
              msg: `failed to get token:${o_token_single.msg}`
            })
          } else {
            continue;
          }
        } else {
          resolve({
            ok: true,
            msg: "ok",
            data: {
              uptoken: o_token_single.data.uptoken
            }
          })
        }
      }
    } else {
      cache_cookie_p = getCookieText();
      let o_re_try = await getQiniuToken();
      resolve(o_re_try)
    }
  })
}

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{phpsessid:String}}>}
 */
function getPhpsessid() {
  return new Promise(resolve => {
    axios.get("http://cookies.liblu.me/apis/soyoung/cookie", {
      validateStatus: s => true,
      timeout: 100 * 1000
    }).then(axresp => {
      if (axresp.data) {
        if (axresp.data.ok
          && axresp.data['data']
          && axresp.data['data']['phpsessid']) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              phpsessid: axresp.data['data']['phpsessid']
            }
          })
        } else if (axresp.data.ok === false && axresp.data['msg']) {
          return CommonAxerrHandlerGen(resolve)(`[cookies.liblu.me]:${axresp.data['msg']}`)
        }
      }
      CommonAxerrHandlerGen(resolve)(axresp.data);
    }
    ).catch(axerr => {
      CommonAxerrHandlerGen(resolve)(axerr);
    })
  })
}


module.exports = {
  getCookieText,
  getQiniuToken,
  __debug: {
    __getQiniuTokenSingle
  }
}